/**
 * @projectName gs_online
 * @package com.answer.wx.gateway.config.filter
 * @className com.answer.wx.gateway.config.filter.RequestFilter
 */
package com.answer.wx.gateway.config.filter;

import com.answer.wx.gateway.config.handler.BodyReaderHttpServletRequestWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * RequestFilter
 * @description 请求过滤器
 * @author answer_wx
 * @date 2022/8/16 16:48
 * @version 1.0
 */
public class RequestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        // 判断是否为json请求
        if (request instanceof HttpServletRequest
                && StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) {
            // 创建缓存装饰器
            requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);
        }
        if (null == requestWrapper) {
            chain.doFilter(request, response);
        } else {
            // 对下面的链路传递缓存装饰器
            chain.doFilter(requestWrapper, response);
        }
    }

    @Override
    public void destroy() {
    }
}